/* eslint-disable react/destructuring-assignment */
/* eslint-disable no-underscore-dangle */
/* eslint-disable no-console */
import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import qs from 'qs';
import download from '@/utils/download';
import { exportQAHistories } from '@/services/download';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import EditQa from '../../KnowledgeManagement/Overview/editQa';
import {
  Card,
  Form,
  Row,
  Col,
  Button,
  Select,
  DatePicker,
  Table,
  Icon,
  Spin,
  message,
  Input,
  Modal,
  Drawer,
  Tooltip,
} from 'antd';
import Relevance from '../../../modules/PopoutRelevance';
import UpDownCharacter from '../../../modules/UpDownCharacter';
import dataTime from '../../../utils/dataTime';
import styles from './index.less';
import { strict } from 'assert';
import { string, object } from 'prop-types';
import moreImg from '@/assets/knowledge/more.png';

// eslint-disable-next-line import/no-unresolved
// const EditQa = React.lazy(() => import('../../KnowledgeManagement/Overview/editQa'));

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const Option = Select.Option;
const Search = Input.Search;
@connect(({ answerRecords, loading }) => ({
  answerRecords,
  loading: loading.effects['answerRecords/fetch'],
}))
class AnswerRecords extends Component {
  constructor() {
    super();
    this.state = {
      upDownDate: [],
      login: false,
      logins: true,
      showModel4: false,
      robotId: '5b2075fc3b000080008e282a', // 问答记录列表参数开始
      from: '',
      to: '',
      page: 1,
      pageSize: 10,
      userId: '',
      resolvedFlag: 0,
      sentiment: '',
      question: '', // 关联列表参数开始
      field: 'q',
      query: '',
      pageA: '',
      pageSizeA: '',
      id: '', // 上下文参数
      loginjqr: false,
      zuid: '',
      shutRelevance: false,
      showModel1: false,
      numberRadio: '1',
      pageSizetwo: 10,
      pagetwo: 1,
      nodeId: '',
      nodeIdName: '所有分类',
      close: false,
      qaId: '',
      isUpdate: false,
      aALeng: '',
      glLeng: 10,
      questiona: '',
      total: 0,
      dataSource: [],
      a: false,
      img: '',
      unknown:''
    };
  }

  fakeAnswerRecords = () => {
    setTimeout(() => {
      this.request(
        this.state.robotId,
        this.state.from,
        this.state.to,
        this.state.page,
        this.state.pageSize,
        this.state.userId,
        this.state.resolvedFlag,
        this.state.sentiment,
        this.state.unknown
      );
    }, 500);
  };

  // eslint-disable-next-line react/sort-comp
  componentDidMount() {
    // console.log(this.state)
    this.request(
      this.state.robotId,
      this.state.from,
      this.state.to,
      this.state.page,
      this.state.pageSize,
      this.state.userId,
      this.state.resolvedFlag,
      this.state.sentiment,
      this.state.unknown
    );
  }

  // 渲染页面前调用一次
  // eslint-disable-next-line react/sort-comp
  componentWillMount() {
    let sysTime = dataTime.formatDate(new Date().getTime()); // 初始时间
    let toTime = moment()
      .subtract('days', 7)
      .format('YYYY/MM/DD'); // 初始时间
    this.setState({
      beginTime: toTime.replace(/\//g, '-'),
      overTime: sysTime.replace(/\//g, '-'),
    });
    console.log(sysTime);
  }

  // 动态获取mock数据
  request = (robotIds, from, to, page, pageSize, userId, resolvedFlag, sentiment,unknown) => {
    this.setState({
      login: true,
    });
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'answerRecords/fetch',
        payload: {
          robotId: currentUser.robotId,
          from,
          to,
          page,
          limit: pageSize,
          userId,
          resolvedFlag,
          sentiment,
          unknown
        },
        callback: res => {
          if (res.list) {
            this.setState({
              login: false,
            });
          }
          res.list.map((item, index) => {
            item['key'] = index;
          });
          console.log(res);
          this.setState({
            dataSource: res.list,
            total: res.total,
          });
        },
      });
    });
  };

  // 获取关联列表数据
  AnswerRelevance = (robotIds, question, field, query, page, pageSize) => {
    this.setState({
      logins: true,
    });
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'answerRecords/fetchb',
      payload: { robotId: currentUser.robotId, question, field, query, page, limit: pageSize },
      callback: res => {
        console.log(res);
        let aA = res.suggestList;
        let bB = res.qaList;
        let aALeng = res.suggestList.length;
        let bBLeng = res.qaList.length;
        console.log(aALeng + bBLeng);
        const total = [...aA, ...bB];
        total.map((item, index) => {
          item['key'] = index;
        });
        this.setState({
          total2: res.total,
          qaListTable: total,
          logins: false,
          aALeng: aALeng,
          glLeng: Number(aALeng + bBLeng),
        });
      },
    });
  };

  // 获取上下文列表数据
  upDownDate = (robotIds, ids) => {
    this.setState({
      // logins: true
      loginjqr: true,
      updowndate: [],
    });
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'answerRecords/fetchc',
      payload: { robotId: this.state.robotIdA, id: this.state.id },
      callback: res => {
        res.list.map((item, index) => {
          item['key'] = index;
        });
        console.log(res);
        this.setState({
          upDownDate: res.list,
          loginjqr: false,
        });
      },
    });
  };

  // 查看
  handleSubmit = () => {
    let userInfo = this.props.form.getFieldsValue(); // 获取数据
    // let usercz = this.props.form.resetFields();// 重置表单数据
    console.log(userInfo);

    let evaluate = userInfo.evaluate; // 0 为全部 1 为解决 -1 为未解决
    if (evaluate === '0') {
      this.setState(
        {
          from: this.state.beginTime,
          to: this.state.overTime,
          resolvedFlag: null,
          page: 1,
          unknown: userInfo.unknown
        },
        () => {
          this.fakeAnswerRecords();
        }
      );
    } else {
      this.setState(
        {
          from: this.state.beginTime,
          to: this.state.overTime,
          resolvedFlag: evaluate,
          page: 1,
          unknown: userInfo.unknown
        },
        () => {
          this.fakeAnswerRecords();
        }
      );
    }
    // console.log(typeof evaluate)
  };

  // 日期选择｛开始日期——结束日期｝
  onChange = (date, dateString) => {
    this.setState({
      beginTime: dateString[0].replace(/\//g, '-'),
      overTime: dateString[1].replace(/\//g, '-'),
      page: 1,
    });

    console.log(date, dateString);
  };

  // eslint-disable-next-line react/sort-comp
  onChangeA = val => {
    // 页数选择
    console.log(val);
    this.setState({
      page: val,
    });
    this.fakeAnswerRecords();
  };

  // 每页显示多少条数据
  onShowSizeChangeA = (current, pageSize) => {
    console.log(current, pageSize);
    this.setState({
      page: current,
      pageSize: pageSize,
    });
    this.fakeAnswerRecords();
  };

  handleDelete = item => {
    console.log('item', item);

    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'answerRecords/fetchd',
      payload: { question: this.state.question, sid: item.sid },
      callback: res => {
        console.log('res', res);
        let a = {};
        if (res.code === 0) {
          message.success('执行成功');
          this.props.form.setFields({ businessName: '' });
          this.setState({ showModel1: false });
        }
      },
    });
  };

  handleDeletes = item => {
    console.log('items', item);
  };

  // 搜索内容
  onFrom = val => {
    console.log('fu', val);
    this.setState(
      {
        pageA: 1,
        pageSizeA: 10,
        query: val,
      },
      () => {
        if (val === '') {
          this.AnswerRelevance(
            this.state.robotId,
            this.state.question,
            this.state.field,
            this.state.query,
            1,
            10
          );
        } else {
          this.AnswerRelevance(this.state.robotId, val, this.state.field, this.state.query, 1, 10);
        }
      }
    );
  };

  // 搜索问题
  onFromA = val => {
    console.log('fu', val);
    let text;
    if (val === '1') {
      text = 'q';
    }
    if (val === '2') {
      text = 'a';
    }
    this.setState({
      pageA: 1,
      pageSizeA: 10,
      field: text,
    });
    setTimeout(() => {
      this.AnswerRelevance(
        this.state.robotId,
        this.state.question,
        this.state.field,
        this.state.query,
        1,
        10
      );
    });
  };

  handleSubmitComment = current => {
    console.log('tcx', current, typeof current);

    this.AnswerRelevance(
      this.state.robotId,
      this.state.question,
      this.state.field,
      this.state.query,
      current,
      this.state.pageSizetwo
    );
  };

  handleSubmitComments = (a, b) => {
    this.setState({ pageSizetwo: b });
    this.AnswerRelevance(
      this.state.robotId,
      this.state.question,
      this.state.field,
      this.state.query,
      a,
      b
    );
  };

  // 上下文组件回调函数
  handleSubUpDwonDate = val => {
    console.log(val);
    this.setState({
      id: val._id,
      robotIdA: val.robotId,
      updowndate: [],
    });
    setTimeout(() => {
      this.upDownDate(this.state.robotId, this.state.id);
    }, 1);
  };

  // 新增按钮
  newlyIncreased = text => {
    console.log('美韩数据', text);
  };

  setClassName = (record, index) => {
    return index < this.state.aALeng ? styles.red : '';
  };

  empty = () => {
    this.setState({ upDownDate: [] });
  };

  export = () => {
    const { dispatch, currentUser } = this.props;
    const data = {
      userId: currentUser.userId,
      from: this.state.beginTime,
      to: this.state.overTime,
      exportFlag: 1,
      resolvedFlag: this.state.resolvedFlag,
    };
    dispatch({
      type: 'answerRecords/listChat',
      payload: data,
      callback: res => {
        let filename = res.requestRes.headers.get('Content-Disposition').split('=')[1];
        download.byBlob(res.fileBlob, filename);
      },
    });
    // exportQAHistories(data, url) listChat
  };

  //  关联方法
  handleOpen = row => {
    this.props.form.setFields({ businessName: '' });
    console.log(row);
    this.setState({ question: row.question, query: '' }, () => {
      this.AnswerRelevance(
        this.state.robotId,
        this.state.question,
        this.state.field,
        this.state.query,
        1,
        10
      );
      this.setState({ showModel1: true, zuid: row.id });
    });
  };

  // 新增
  addhandleOpen = row => {
    console.log(row, Array(row.question));
    this.setState(
      {
        qaId: Array(row.question.replace(/<.*?>/g, '')),
      },
      () => {
        this.setState({ close: true });
      }
    );
  };

  onClose = () => {
    this.setState({
      close: false,
      // isUpdate: true
    });
  };

  openGaller = item => {
    this.setState({
      img: item,
      a: true,
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const columns1 = [
      {
        title: '问题',
        dataIndex: 'question',
        width: 'calc(30vw)',
        render(item) {
          return (
            <div className={styles.hull}>
              <span>{item}</span>
            </div>
          );
        },
      },
      {
        title: '分类',
        dataIndex: 'category',
        width: 'calc(30vw)',
        render(item) {
          return (
            <div className={styles.hull}>
              <span>{item}</span>
            </div>
          );
        },
      },
      {
        title: '操作',
        render: (text, item) => {
          return (
            <div className={styles.pb}>
              <div
                className={styles.buttongl}
                onClick={text => {
                  this.handleDelete(item);
                }}
              >
                {/* <MyIcon  type="icon-bi" /> */}
                <span>
                  <Icon size="small" type="link" style={{ marginRight: 5 }} />
                </span>
                <span>关联</span>
              </div>
            </div>
          );
        },
      },
    ];

    const columns = [
      {
        title: '问题',
        width: 'calc(15vw)',
        dataIndex: 'question',
        render(item) {
          return (
            // <div className={styles.wtbj}>{item}</div>
            <div className={styles.wtbj} dangerouslySetInnerHTML={{ __html: item }} />
          );
        },
      },
      {
        title: '回答',
        width: 'calc(20vw)',
        dataIndex: 'answer',
        render: item => {
          if (item.indexOf('img') != -1) {
            let a = item.replace('img', 'img style="max-width:100%"');
            return (
              <div
                className={styles.hdbj}
                onClick={() => this.openGaller(a)}
                style={{ maxWidth: 388, wordBreak: 'break-word', paddingLeft: 2 }}
              >
                <div className={styles.hdbjB} dangerouslySetInnerHTML={{ __html: a }} />
              </div>
            );
          } else {
            return (
              <div
                className={styles.hdbj}
                style={{ maxWidth: 388, wordBreak: 'break-word', paddingLeft: 2 }}
              >
                <div>
                  <div className={styles.hdbjB} dangerouslySetInnerHTML={{ __html: item }} />
                </div>
              </div>
            );
          }
        },
      },
      {
        title: '访客',
        width: 'calc(10vw)',
        dataIndex: 'userId',
      },
      {
        title: '触发未知问题',
        width: 'calc(10vw)',
        dataIndex: 'sid',
        render(item){
            return(
              <div style={{textAlign:'center'}}>
                {
                  item ==='NOT_FOUND'?'是':"否"
                }
              </div>
            )
        }
      },
      {
        title: '评价',
        dataIndex: 'resolvedFlag',
        render(state) {
          if (state === 0) {
            return <div />;
          }
          if (state === 1) {
            return (
              <div className={styles.badgeDangera}>
                <div className={styles.badgeDangerB}>
                  <Icon style={{ color: '#ffffff' }} type="like" />
                </div>
              </div>
            );
          }
          return (
            <div className={styles.badgeDangerA}>
              <div className={styles.badgeDangerB}>
                <Icon style={{ color: '#ffffff' }} type="dislike" />
              </div>
            </div>
          );
        },
      },
      {
        title: '时间',
        dataIndex: 'createTime',
        width: 'calc(10vw)',
        render(dataIndex) {
          return moment(dataIndex).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '操作',
        width: 'calc(10vw)',
        render: (text, item) => {
          return (
            <div >
              <div className={styles.tool}>
                  <Button
                    type="primary"
                    icon="link"
                    size="small"
                    onClick={() => this.handleOpen(item)}
                  >
                  </Button>
                  <Button
                    onClick={() => this.addhandleOpen(item)}
                    style={{ margin: '0px 5px' }}
                    disabled={this.state.showModel4}
                    type="primary"
                    icon="plus"
                    size="small"
                  >
                  </Button>
                  <span>
                    <UpDownCharacter
                    text={text}
                    icons="bars"
                    title="聊天上下文"
                    updowndate={this.state.upDownDate}
                    onSubmitA={this.handleSubUpDwonDate}
                    loginjqr={this.state.loginjqr}
                    empty={this.empty}
                  /></span>
              </div>
              <img src={moreImg} alt="" className={styles.more} />
            </div>
          );
        },
      },
    ];
    // console.log(this.state.qaId,this.state)
    return (
      <Suspense fallback={<PageLoading />}>
          <div >
              <div>
                <p style={{ marginLeft: 20, marginTop: 10 }} className="titleA">
                  问答记录
                </p>
                <Row>
                  <Col span={12} xs={24} sm={24} md={24} lg={20} xl={16} offset={8} className={styles.zsy}>
                    <Form className={styles.buttonA} layout="inline">
                      <FormItem>
                        {getFieldDecorator('unknown', {
                          initialValue: '', // 初始值
                        })(
                          <Select style={{ width: 160 }}>
                            <Option value="">
                             触发未知问题
                            </Option>
                            <Option value="1">
                             否
                            </Option>
                            <Option value="0">
                              是
                            </Option>
                          </Select>
                        )}
                      </FormItem>
                      <FormItem>
                        {getFieldDecorator('evaluate', {
                          initialValue: '0', // 初始值
                        })(
                          <Select style={{ width: 160 }}>
                            {/* <Option value='1'>选择用户评价</Option> */}
                            <Option value="0">
                              <FormattedMessage
                                id="app.answerRecords.user-evaluate"
                                defaultMessage="User evaluate"
                              />
                            </Option>
                            <Option value="1">
                              <FormattedMessage
                                id="app.answerRecords.resolved"
                                defaultMessage="Resolved"
                              />
                            </Option>
                            <Option value="-1">
                              <FormattedMessage
                                id="app.answerRecords.unsolved"
                                defaultMessage="Ussolved"
                              />
                            </Option>
                          </Select>
                        )}
                      </FormItem>
                      <FormItem>
                        <RangePicker
                          onChange={this.onChange}
                          style={{ width: 250 }}
                          defaultValue={[
                            moment(this.state.beginTime, dateFormat),
                            moment(this.state.overTime, dateFormat),
                          ]}
                          format={dateFormat}
                        />
                      </FormItem>

                      <FormItem className="buttonYs">
                        <Button onClick={this.handleSubmit} icon="check">
                          {/* 查看 */}
                          <FormattedMessage id="app.answerRecords.examine" defaultMessage="Examine" />
                        </Button>
                      </FormItem>

                      <FormItem className="buttonYs">
                        <Button onClick={this.export} icon="arrow-down">
                          {/* 下载 */}
                          <FormattedMessage
                            id="app.answerRecords.download"
                            defaultMessage="Download"
                          />
                        </Button>
                      </FormItem>
                    </Form>
                  </Col>
                </Row>
              </div>
              <Spin  spinning={this.state.login}>
                <div className={styles.dabj} style={{ padding: '0px 20px' }}>
                  <div className={styles.border} style={{ position: 'relative', right: '2px' }}>
                    <Table
                      className="zdyTable"
                      // style={{ padding: '20px 20px 0px 20px' }}
                      //  bordered // 网格
                      // scroll={{y:' calc(100vh - 400px)'}}
                      columns={columns}
                      dataSource={this.state.dataSource}
                      pagination={{
                        // 分页
                        total: this.state.total, // 数据总数量
                        pageSize: this.state.pageSize, // 显示几条一页
                        current: this.state.page, // 默认显示几条一页
                        showSizeChanger: true, // 是否显示可以设置几条一页的选项
                        showQuickJumper: true,
                        onChange: this.onChangeA,
                        onShowSizeChange: this.onShowSizeChangeA,
                      }}
                    />
                  </div>
                </div>
              </Spin>
              <Modal
                style={{ top: 60 }}
                width={'calc( 70vw)'}
                className={styles.overa}
                title="添加关联知识点"
                visible={this.state.showModel1}
                footer={null}
                onCancel={() => {
                  this.setState({
                    showModel1: false,
                  });
                }}
                onOk={() => {
                  // 确定方法不开出去
                  this.setState({
                    showModel1: false,
                  });
                }}
              >
                <Form layout="inline" style={{ paddingBottom: 20 }}>
                  <FormItem style={{ marginLeft: 20 }}>
                    <Select
                      defaultValue={this.state.numberRadio}
                      style={{ width: 160 }}
                      onChange={this.onFromA}
                    >
                      <Option value="1">搜索问题</Option>
                      <Option value="2">搜索答案</Option>
                    </Select>
                  </FormItem>
                  <FormItem>
                    {getFieldDecorator('businessName', {
                      initialValue: '',
                    })(
                      <Search
                        placeholder="请输入搜索内容"
                        onSearch={value => {
                          this.onFrom(value);
                        }}
                        style={{ width: 320 }}
                      />
                    )}
                  </FormItem>
                </Form>
                <Spin spinning={this.state.logins}>
                  <Table
                    rowClassName={this.setClassName}
                    className={styles.over}
                    //  bordered
                    columns={columns1}
                    dataSource={this.state.qaListTable}
                    pagination={{
                      // 分页
                      total: this.state.total2, // 数据总数量
                      pageSize: this.state.glLeng, // 显示几条一页
                      defaultPageSize: this.state.pagetwo, // 当前页
                      // showSizeChanger: true,  // 是否显示可以设置几条一页的选项
                      showQuickJumper: true,
                      onChange: this.handleSubmitComment,
                      onShowSizeChange: this.handleSubmitComments,
                    }}
                  />
                </Spin>
              </Modal>
              <Modal
                style={{ maxHeight:' 90%',display: 'flex',justifyContent:'center',alignItems:'center'}}
                width={'calc(80vw)'}
                height={'calc(80vh)'}
                className='modalovel'
                visible={this.state.a}
                title="图片详情"
                onCancel={() => {
                  this.setState({
                    a: false,
                  });
                }}
                footer={null}
              >
                {<div dangerouslySetInnerHTML={{ __html: this.state.img }} />}
              </Modal>
              <Drawer
                title={<FormattedMessage id="app.overView.editQa" />}
                placement="right"
                closable={false}
                onClose={this.onClose}
                visible={this.state.close}
                width={800}
                destroyOnClose
              >
                <EditQa qaId="" questions={this.state.qaId} onClose={this.onClose} />
              </Drawer>
          </div>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(AnswerRecords));
